import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Select, Button, Space, List, Modal, message, Switch } from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';

const { Option } = Select;

interface MCPConfig {
  id?: string;
  type: 'http' | 'sse';
  url: string;
  tools?: string[];
  headers?: Record<string, string>;
  enabled?: boolean;
  name?: string;
  description?: string;
}

interface MCPManagerProps {
  onConfigChange?: (configs: MCPConfig[]) => void;
}

export const MCPManager: React.FC<MCPManagerProps> = ({ onConfigChange }) => {
  const [configs, setConfigs] = useState<MCPConfig[]>([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingConfig, setEditingConfig] = useState<MCPConfig | null>(null);
  const [form] = Form.useForm();

  // 加载保存的配置
  useEffect(() => {
    loadConfigs();
  }, []);

  const loadConfigs = async () => {
    try {
      const result = await chrome.storage.sync.get(['mcpConfig']);
      const savedConfigs = result.mcpConfig || [];
      setConfigs(savedConfigs);
    } catch (error) {
      console.error('Failed to load MCP configs:', error);
    }
  };

  const saveConfigs = async (newConfigs: MCPConfig[]) => {
    try {
      await chrome.storage.sync.set({ mcpConfig: newConfigs });
      setConfigs(newConfigs);
      onConfigChange?.(newConfigs);
      message.success('MCP 配置已保存');
    } catch (error) {
      console.error('Failed to save MCP configs:', error);
      message.error('保存 MCP 配置失败');
    }
  };

  const handleAdd = () => {
    setEditingConfig(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (config: MCPConfig) => {
    setEditingConfig(config);
    form.setFieldsValue({
      ...config,
      tools: config.tools?.join(', ') || '',
      headers: JSON.stringify(config.headers || {}, null, 2),
    });
    setIsModalVisible(true);
  };

  const handleDelete = (configId: string) => {
    const newConfigs = configs.filter(c => c.id !== configId);
    saveConfigs(newConfigs);
  };

  const handleToggleEnabled = (configId: string) => {
    const newConfigs = configs.map(c => 
      c.id === configId ? { ...c, enabled: !c.enabled } : c
    );
    saveConfigs(newConfigs);
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      
      // 处理工具列表
      const tools = values.tools ? 
        values.tools.split(',').map((tool: string) => tool.trim()).filter(Boolean) : 
        [];
      
      // 处理头部信息
      let headers = {};
      if (values.headers) {
        try {
          headers = JSON.parse(values.headers);
        } catch (error) {
          message.error('Headers JSON 格式错误');
          return;
        }
      }

      const newConfig: MCPConfig = {
        ...values,
        id: editingConfig?.id || Date.now().toString(),
        tools,
        headers,
        enabled: values.enabled !== false,
      };

      let newConfigs;
      if (editingConfig) {
        newConfigs = configs.map(c => c.id === editingConfig.id ? newConfig : c);
      } else {
        newConfigs = [...configs, newConfig];
      }

      await saveConfigs(newConfigs);
      setIsModalVisible(false);
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const testConnection = async (config: MCPConfig) => {
    try {
      message.loading('正在测试连接...', 0);
      
      if (config.type === 'http') {
        const response = await fetch(`${config.url}/health`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            ...config.headers,
          },
        });
        
        if (response.ok) {
          message.destroy();
          message.success('连接测试成功');
        } else {
          message.destroy();
          message.error(`连接测试失败: ${response.statusText}`);
        }
      } else {
        // SSE 连接测试
        const eventSource = new EventSource(config.url);
        const timeout = setTimeout(() => {
          eventSource.close();
          message.destroy();
          message.error('连接测试超时');
        }, 5000);

        eventSource.onopen = () => {
          clearTimeout(timeout);
          eventSource.close();
          message.destroy();
          message.success('SSE 连接测试成功');
        };

        eventSource.onerror = () => {
          clearTimeout(timeout);
          eventSource.close();
          message.destroy();
          message.error('SSE 连接测试失败');
        };
      }
    } catch (error) {
      message.destroy();
      message.error(`连接测试失败: ${error.message}`);
    }
  };

  return (
    <Card title="MCP 工具配置" style={{ margin: '16px 0' }}>
      <Space direction="vertical" style={{ width: '100%' }}>
        <Button 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleAdd}
        >
          添加 MCP 连接
        </Button>

        <List
          dataSource={configs}
          renderItem={(config) => (
            <List.Item
              actions={[
                <Button 
                  key="test"
                  size="small" 
                  onClick={() => testConnection(config)}
                >
                  测试连接
                </Button>,
                <Button 
                  key="edit"
                  size="small" 
                  icon={<EditOutlined />} 
                  onClick={() => handleEdit(config)}
                >
                  编辑
                </Button>,
                <Button 
                  key="delete"
                  size="small" 
                  danger 
                  icon={<DeleteOutlined />} 
                  onClick={() => handleDelete(config.id!)}
                >
                  删除
                </Button>,
              ]}
            >
              <List.Item.Meta
                title={
                  <Space>
                    {config.name || config.url}
                    <Switch
                      size="small"
                      checked={config.enabled !== false}
                      onChange={() => handleToggleEnabled(config.id!)}
                    />
                  </Space>
                }
                description={
                  <div>
                    <div>类型: {config.type.toUpperCase()}</div>
                    <div>URL: {config.url}</div>
                    {config.tools && config.tools.length > 0 && (
                      <div>工具: {config.tools.join(', ')}</div>
                    )}
                    {config.description && (
                      <div>描述: {config.description}</div>
                    )}
                  </div>
                }
              />
            </List.Item>
          )}
        />
      </Space>

      <Modal
        title={editingConfig ? '编辑 MCP 配置' : '添加 MCP 配置'}
        open={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => setIsModalVisible(false)}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            type: 'http',
            enabled: true,
          }}
        >
          <Form.Item
            name="name"
            label="配置名称"
            rules={[{ required: true, message: '请输入配置名称' }]}
          >
            <Input placeholder="例如: 本地工具服务器" />
          </Form.Item>

          <Form.Item
            name="type"
            label="连接类型"
            rules={[{ required: true }]}
          >
            <Select>
              <Option value="http">HTTP</Option>
              <Option value="sse">Server-Sent Events (SSE)</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="url"
            label="服务器 URL"
            rules={[
              { required: true, message: '请输入服务器 URL' },
              { type: 'url', message: '请输入有效的 URL' }
            ]}
          >
            <Input placeholder="http://localhost:3000/mcp" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea 
              rows={2} 
              placeholder="描述这个 MCP 连接的用途..." 
            />
          </Form.Item>

          <Form.Item
            name="tools"
            label="启用的工具"
            help="工具名称，用逗号分隔。留空表示启用所有工具。"
          >
            <Input placeholder="web_search, file_operations, database_query" />
          </Form.Item>

          <Form.Item
            name="headers"
            label="HTTP Headers (JSON 格式)"
            help="可选的认证头或其他 HTTP 头信息"
          >
            <Input.TextArea 
              rows={4} 
              placeholder='{\n  "Authorization": "Bearer your-token",\n  "X-API-Key": "your-api-key"\n}'
            />
          </Form.Item>

          <Form.Item
            name="enabled"
            valuePropName="checked"
          >
            <Switch /> 启用此配置
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};